package criptosuma.formulation;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import es.deusto.ingenieria.is.csp.algorithms.CSPAlgorithm;
import es.deusto.ingenieria.is.csp.formulation.CSPProblem;

public class CriptosumaProblem extends CSPProblem<Integer> 
{	
	public CriptosumaProblem(String fileName)
	{
		CriptosumaXMLParser xml = new CriptosumaXMLParser(fileName);
		this.addVariables(xml.getVariables());
		
		/*
		//COMPROBACION DE RESTRICCIONES PARA CADA VARIABLE 	
		System.out.println("Variables a criptosuma: " + getVariables());
		for (Variable<Integer> variable : getVariables()) 
		{
			System.out.println("Variable: " + variable.getName());
			ArrayList<Constraint<Integer>> c = new ArrayList<Constraint<Integer>>(variable.getConstraints());
			for (Constraint<Integer> constraint : c) 
			{
				System.out.println("restric: " + constraint.getName() + ". Vars: " + constraint.getVariables());
				if(constraint instanceof SumConstraint)
				{
					System.out.println("        left: " + ((SumConstraint)constraint).getLeft());
					System.out.println("        right: " + ((SumConstraint)constraint).getRight());
				}
	
			}
			System.out.println();
		}
		System.out.println(this);*/
	}
	
	@Override
	public String toString()
	{
		return getVariables().toString();
	}
	
	public void solve(CSPAlgorithm<Integer> algorithm)
	{
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss.S");
		Date beginDate = GregorianCalendar.getInstance().getTime();
		System.out.println("\n* Start '" + algorithm.getClass().getSimpleName() + "' (" + formatter.format(beginDate) + ")");				
		boolean solutionFound = algorithm.solve(this);
		Date endDate = GregorianCalendar.getInstance().getTime();		
		System.out.println("* End   '" + algorithm.getClass().getSimpleName() + "' (" + formatter.format(endDate) + ")");
		
		long miliseconds = (int) Math.abs(beginDate.getTime() - endDate.getTime());
		long seconds = miliseconds / 1000;
		miliseconds %= 1000;		
		long minutes = seconds / 60;
		seconds %= 60;
		long hours = minutes / 60;
		minutes %= 60;
		
		String time = "\n* Serach lasts: ";
		time += (hours > 0) ? hours + " h " : " ";
		time += (minutes > 0) ? minutes + " m " : " ";
		time += (seconds > 0) ? seconds + "s " : " ";
		time += (miliseconds > 0) ? miliseconds + "ms " : " ";
		
		System.out.println(time);
		
		if (solutionFound) {
			System.out.println("\n- :-) Solution found!");			
			System.out.println("\n" + this);
		} else {
			System.out.println("\n- :-( Unable to find the solution!");
		}
	}
}
